/**
 * 正则表达式学习
 */
var reg = /{([\w\.]+)}/g;
var str = 'Hello {name}!欢迎来自{address.province} {address.city}{age.number.zz}';
//console.log(str.match(reg))
//console.log(str);
//console.log(str.search(reg));
var person ={
    name :'dongge',
    address:{
        //province:'湖北省',
        //city:'荆州市'
    },
    age:{
        number:{
            zz:'dd'
        }
    }
};
//var rpStr = str.replace(reg,function(match,p1,offset,string){
//    console.log(match);
//    console.log(p1);
//    if(p1.indexOf('.')){
//        //var ps = p1.split('.');
//        var ps = p1.slice();
//        console.log(ps);
//    }
//    return person[p1];
//});
//console.log(rpStr);
/**
 * sample 1:
 * '''js
 * var template = 'Hello {name}!'
 * var obj = {name:'John'}
 * console.log(replace(template,obj)) //out: Hello John!
 *
 * '''js
 * sample 2:
 * var template = 'Hello {user.name}!'
 * var obj = {user:{name:'Christoper Smith'}};
 * console.log(replace(template,obj))//out:Hello Christoper Smith!
 * @param template
 * @param obj
 * @returns {*}
 */
function replace(template,obj){
    var pattern = /{([_\w\.]+)}/g;
    return template.replace(pattern,function(match,p1,offset,string){
        var arr = p1.split('.');
        if(arr.length > 1){
            var i = 0;
            var len = arr.length;
            var subObj = obj[arr[0]];
            while(typeof subObj === 'object' && i < len){
                i = i + 1;
                subObj = subObj[arr[i]];
            }
            if(i === len-1){
                if(subObj === undefined){
                    return "";
                }else{
                    return subObj;
                }
            }else {
                return "";
            }
        }else{
            var ret = obj[p1]
            if(ret === undefined)
            {
                return "";
            }else{
                return ret;
            }
        }

    })
}
//console.log(replace(str,person));


var template = '<article id="{_id}" class="post tag-about-ghost tag-release"><div class="post-head">' +
    '<h1 class="post-title">' +
    '<a href="/article/detail?id={_id}">{title}</a></h1>'+
    '<div class="post-head"><h1 class="post-title"><a href="/article/detail?id={_id}">{title}</a></h1><div class="post-meta"><span class="author">作者：<a href="/article/list?userId={user._id}">{user.username}</a></span> •'+
    '<time>{date}</time></div></div>'+
    '<div class="post-content">'+
        '<p>{body}</p>'+
    '</div>'+
    '<div class="post-permalink"><a href="/article/detail?id={_id}" class="btn btn-default">阅读全文</a></div>'+
    '<footer class="post-footer clearfix"><div class="pull-left tag-list"><i class="fa fa-folder-open-o"></i><a href="#">Ghost</a>, <a href="#">新版本发布</a></div><div class="pull-right share"></div></footer>'+
    '</article>';
var article = {
    _id:'246543165464654',
    title:'这个是个问题',
    body:'苴侯求救于秦，蜀王杜芦也派使者与秦结盟，目的是不希望秦干涉苴政。但狡诈的秦惠王嬴驷收了二国的礼物后，派张仪、张若、司马错率队走石牛道（今剑阁金牛道/剑阁道）灭蜀吞苴，蜀王身死，苴侯被废，蜀太子逃到彭乡（今彭州）被捉。《本蜀论》记载惠文王用计灭古蜀：“秦惠王欲伐蜀而不知道(路)，作五石牛，以金置尾下，言能屎金，蜀王负力，令五丁引之，成(蜀)道。秦使张仪、司马错寻路灭蜀，因曰石牛道。”秦惠王任蜀太子为蜀侯，张若为蜀相，置蜀郡。宣告蜀、苴二国灭亡。',
    user:{
        _id:'56465432131654',
        username:'dongge'
    },
    date:'2015-12-5'
}
//console.log(replace(template,article));s
//console.log(template);
/**************************************/
var pa = /m+/g;
//console.log(pa.test('mm-dd'));
//console.log(pa.exec('mm-mm'));
/**
 * dateFormat(new Date(),'{y}年{M}月{d}日 {h}点{m}分{s}秒')
 * @param date
 * @param fmt
 * @returns {*}
 */
function dateFormat(date,fmt){
    if(date instanceof Date){
        date = {
            y:date.getFullYear(),
            M:date.getMonth(),
            d:date.getDay(),
            h:date.getHours(),
            m:date.getMinutes(),
            s:date.getSeconds()
        };
        return replace(fmt,date);
    }else {
        return '';
    }

}
console.log(dateFormat(new Date(),'{y}年{M}月{d}日 {h}点{m}分{s}秒'));

/**
 * 匹配字符串中的变量[A-Za-z_]
 */

var p = /(("?)([A-Za-z_]\w*)\2)/g;
var str = 'name ==="dongge"';
//console.log(p.exec(str));
var match = p.exec(str);
while(match){
    //console.log(match);
    match = p.exec(str);
}

var obj = {name:'dongge'};
function print(){
    //console.log(this.name);
}
print.call(obj);

function addThis(str){
    var pattern = /(("?)([A-Za-z_]\w*)\2)/g;
    return str.replace(pattern,function (match,p1,p2,p3){
        if(p2 === '"'){
            return p1;
        }
        else{
            return "this."+p3;
        }
    })
}
//console.log(addThis(str))

var ifstr = '<if test={name === "dongge"}>If test</if>';
var fpattern =/<(iterator|property|if)([^>]*)>(.*)<\/\1>/;
var tp = '<iterator value={names}>我是<property value={top}></property></iterator>';
var tp1 = '<if test={top > 3}><property value={top}></property> is bigger than 3</if>';
var fpattern1 = /<(iterator|property|if)\s*(\w+\s*=\s*\{[^}]*})>(.*?)<\/\1>/g;
//console.log(fpattern.exec(ifstr));
//console.log(fpattern.exec(tp));
//console.log(fpattern1.exec(ifstr));
//console.log(fpattern1.exec(tp));
//console.log(fpattern1.exec(tp1));
var tp4 = '<article id="<property value={_id}></property>" class="post tag-about-ghost tag-release">'+
    '<div class="post-head">'+
    '<h1 class="post-title"><a href="/article/detail?id=<property value={_id}></property>"><property value={title}></property></a></h1>'+
    '<div class="post-meta">'+
    '<span class="author">作者：<a href="/article/list?userId={user._id}"><property value={user.username}></property></a></span> •'+
    '<time><property value={date}></property></time></div></div>'+
    '<div class="post-content"><p><property value={body}></property></p></div>'+
    '<footer class="post-footer clearfix">'+
    '<div class="pull-left tag-list">'+
    '<i class="fa fa-folder-open-o"></i>'+
    '<a href="#">Ghost</a>, <a href="#">新版本发布</a></div>'+
    '<div class="pull-right share"></div></footer></article>';
var match1 = fpattern1.exec(tp4);
while(match1){
    //console.log(match1);
    match1 = fpattern1.exec(tp4);
}
/******************greedy问题*/
var tds = '<td></td><td></td><td></td>';
var tdpattern = /<td>.*<\/td>/;
var match2 = tdpattern.exec(tds);
//console.log(match2);//会匹配<td></td><td></td><td></td>
var tdpattern1 = /<td>.*?<\/td>/;
var match3 = tdpattern1.exec(tds);
//console.log(match3);//只会匹配一个<td></td>
//这就是贪婪问题 加了？之后能将表达式变为不贪婪匹配
+function(){
    var pattern =/<(iterator|property|if)\s*(\w+\s*=\s*\{[^}]*})>([.\n\r]*?)<\/\1>/g;
    var pattern1 =/<(iterator)\s*(\w+\s*=\s*\{[^}]*})>([.\r\n]*?)<\/\1>/g;
    var tds1 = '<td>/r/ndd</td><td></td>'
    var iterator = '<iterator value={articles}>\r\n' +
        '</iterator>';
    var tdp = /<td>(.*?)<\/td>/g;
    var tp11 =
        '<iterator value={articles}>\r\n'+
        /*'<article>'+
        '<div class="header">'+
        '<h3><property value={title}></property></h3>'+
        '<p><span>作者：<a href="/article/">东哥</a></span>&nbsp;<span><property value={date}></property></span></p>'+
        '</div>'+
        '<div class="content">'+
        '<p><property value={content}></property></p>'+
        '<a href="/article/get?id=<property value={_id}></property>">更多</a>'+
        '</div>'+
        '<div class="keys">'+
        '<span><property value={keys}></property></span>'+
        '</div>'+
        '</article>'+*/
        '\r\n'+
        '</iterator>';
    //var m = tdp.exec(tds1);
    //while(m = tdp.exec(tds1)){
    //while(m = pattern.exec(tp11)){
    while(m = pattern1.exec(tp11)){
        //console.log(m);
    }
}();

+function(){
    var pattern = /^[\r\n.]*$/;
    var pattern1 =/^[.]*$/;
    var pattern2 = /^[123]*$/;
    var pattern3 = /^.*$/;
    var pattern4 = /^.*$/m;
    var pattern5 = /^[^]*$/;
    var pattern6 = /^[\s\S]*$/;
    console.log(pattern.test('\r\n'));//true
    console.log(pattern.test('\r\n11'));//false
    console.log(pattern1.test('abc'));//false
    console.log(pattern2.test('123123'));//true
    console.log(pattern3.test('\r\n'));//false
    console.log(pattern4.test('\r\n'));//true
    console.log(pattern5.test('\r\n11'));//true
    console.log(pattern6.test('\r\n11'));//true
}();


